package selectionweb.web.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import selectionweb.web.Ingredient;
import selectionweb.web.Ingredient.Type;
import selectionweb.web.Student;
import selectionweb.web.Course;


import javax.validation.Valid;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Slf4j
@Controller
@Configuration
@RequestMapping("/selection")
public class SelectionController {
    public Student student;
    public static Object object;
    private static String readJson(String path) {

        //从指定位置读取文件
        File file = new File(path);

        BufferedReader br = null;

        //返回值，使用StringBuffer
        StringBuffer data = new StringBuffer();
        try {
            br = new BufferedReader(new FileReader(file));
            //每次读取文件的缓存
            String temp = null;
            while ((temp = br.readLine()) != null) {
                data.append(temp);
                object=data;
                System.out.println(object);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("读取成功！");
        return data.toString();
    }

    /**
     * 向文件中写入数据
     * @param path 文件路径
     * @param json  json数据
     * @param fileName 文件名称
     */
    private static void writeJson(String path, Object json, String fileName) {
        BufferedWriter bw = null;
        File file = new File(path + fileName);

        //如果文件不存在，则新建一个
        if (! file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //写入数据
        try {
            bw = new BufferedWriter(new FileWriter(file));
            bw.write(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("写入成功！");
    }

    @ModelAttribute
    public void addIngredientsToModel(Model model) {
        List<Ingredient> ingredients = Arrays.asList(
                new Ingredient("A", "语文", Type.SUBJECT),
                new Ingredient("B", "数学", Type.SUBJECT),
                new Ingredient("C", "英语", Type.SUBJECT),
                new Ingredient("D", "物理", Type.SUBJECT),
                new Ingredient("E", "化学", Type.SUBJECT),
                new Ingredient("F", "生物", Type.SUBJECT)
        );

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }
    }

    @GetMapping
    public String showDesignForm(Model model) {
        model.addAttribute("selection", new Course());
        return "selection";
    }

    @PostMapping
    public String processDesign(@Valid Course course, Errors errors, Model model) {
        if (errors.hasErrors()) {
            return "selection";
        }

        log.info("Processing design: " + course);
        readJson("D://student.txt");
        String a=object.toString();
        model.addAttribute("selection", a);
        System.out.println(a);
        return "selectionResult";
    }

    private List<Ingredient> filterByType(
            List<Ingredient> ingredients, Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}

